package com.smiier.skin.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.FlowLayout;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.evan.common.task.RequestTask;
import com.evan.common.utils.CacheCommon;
import com.pifuke.adapter.QuestionAdapter;
import com.smiier.skin.QuestionDetailActivity;
import com.smiier.skin.SearchQuestionActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.QuestionGetListTask;
import com.smiier.skin.net.QuestionGetListTask.QuestionGetListRequest;
import com.smiier.skin.net.QuestionGetListTask.QuestionGetListResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.DBUtil;

public class QuestionFragment extends BasicFragment implements
		OnRefreshListener<ListView>, View.OnClickListener {

	protected QuestionGetListRequest mRequest = new QuestionGetListRequest();

	PullToRefreshListView list_question;
	QuestionAdapter adapter;
	long start_qid;
	int pageIndex;
	Button btn_search;

	View view_filter;

	//private TextView text_empty;

	QuestionReceiver questionReceiver;

	public QuestionFragment(Context context) {
		super(context);
	}

	public QuestionFragment(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public QuestionFragment(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.setContentView(R.layout.fragment_question);
		init();
		back.setOnClickListener(this);
		text_right.setOnClickListener(this);
		setNavTitle("咨询");
		setNavLeftBtnDrawable(R.drawable.icon_question_type);
		list_question = findViewById(R.id.list_question,
				PullToRefreshListView.class);
	//	text_empty = findViewById(R.id.text_empty, TextView.class);

		// 设置头部搜索框
		View headView = LayoutInflater.from(getContext()).inflate(
				R.layout.view_search_button, null);
		headView.findViewById(R.id.btn_search).setOnClickListener(this);
		list_question.getListView().addHeaderView(headView);
		list_question.setOnRefreshListener(this);

		list_question.setPullLoadEnabled(true);
		list_question.setScrollLoadEnabled(true);

		adapter = new QuestionAdapter();
		adapter.setDataProvider(new ArrayList<QuestionAnswer>());

		mRequest.pageSize = GlobalSettings.PAGE_SIZE;
		mRequest.token = GlobalSettings.sToken;

		// 如果不是医生，则显示的是已经解答的问题

		Log.i("testchat",
				"CommonUtility.isDoctor():" + (CommonUtility.isDoctor()));

		if (!CommonUtility.isDoctor()) {
			mRequest.statuses = new ArrayList<Integer>();
			mRequest.statuses.add(3);
		} else {
			mRequest.statuses = new ArrayList<Integer>();
			mRequest.statuses.add(1);
		}
		//list_question.doPullRefreshing(true);
		list_question
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> adapterView,
							View view, int postion, long id) {
						try {
							Intent intent = new Intent(getContext(),
									QuestionDetailActivity.class);
							int mPositon = postion - 1;

							intent.putExtra(Constant.IDENTITY_KEY,
									JsonUtil.convert(adapter.getItem(mPositon)));
							startActivity(intent);
						} catch (Exception e) {

						}
					}
				});

		btn_search = findViewById(R.id.btn_search, Button.class);
		registerReceiver();
	}

	@Override
	public void onResume() {
		super.onResume();
		start_qid = 0;
		pageIndex = 0;
		adapter.getDataProvider().clear();
		adapter.notifyDataSetChanged();
		loadData(false);
	}

	@Override
	public boolean onInterceptBackPressed() {
		if (CommonUtility.indexOf((Activity) getContext(), view_filter) != -1) {
			CommonUtility.removeView((Activity) getContext(), view_filter,
					R.anim.push_left_out);
			return true;
		}
		return super.onInterceptBackPressed();
	}

	protected void init() {
		back = findViewById(R.id.btn_left, TextView.class);
		text_nav = findViewById(R.id.text_nav, TextView.class);
		text_right = findViewById(R.id.text_right, TextView.class);
	}

	protected void setNavTitle(String title) {
		if (!CommonUtility.isNull(text_nav)) {
			text_nav.setText(title);
		}
	}

	protected void setNavRightBtn(String title) {
		if (!CommonUtility.isNull(text_right)) {
			text_right.setVisibility(View.VISIBLE);
			text_right.setText(title);
		}
	}

	protected void setNavLeftBtnDrawable(int resid) {
		if (!CommonUtility.isNull(back)) {
			back.setText(null);
			setNavLeftBtnNoDrawable();
			LayoutParams params = (LayoutParams) back.getLayoutParams();
			params.width = CommonUtility.dip2px(getContext(), 34);
			params.height = CommonUtility.dip2px(getContext(), 26);
			back.setLayoutParams(params);
			back.setBackgroundResource(resid);
		}
	}

	protected void setNavLeftBtnNoDrawable() {
		if (!CommonUtility.isNull(back)) {
			back.setCompoundDrawables(null, null, null, null);
		}
	}

	private void registerReceiver() {
		IntentFilter filter = new IntentFilter(Constant.RECIVER_QUESTION);
		questionReceiver = new QuestionReceiver();
		getContext().registerReceiver(questionReceiver, filter);
	}

	private void loadData(boolean isShowDialog) {
	/*	if(adapter.getDataProvider()!=null&&adapter.getDataProvider().size()>0){
			list_question.setContextEmptyType(false, 2);
		}else{
			list_question.setContextEmptyType(true, 4);
		}*/
		mRequest.startQid = start_qid;
		mRequest.pageIndex = ++pageIndex;
		mRequest.token = GlobalSettings.sToken;
		QuestionGetListTask task = new QuestionGetListTask();
		task.setRequest(mRequest);
		task.addListener(new NetTaskListener<QuestionGetListTask.QuestionGetListRequest, QuestionGetListTask.QuestionGetListResponse>() {

			@Override
			public void onException(
					INetTask<QuestionGetListRequest, QuestionGetListResponse> task,
					Exception e) {
				list_question.doComplete();
				if(adapter.getDataProvider()!=null&&adapter.getDataProvider().size()>0){
					list_question.setContextEmptyType(false, 2);
				}else{
					list_question.setContextEmptyType(true, 4);
				}
			}

			@Override
			public void onComplete(
					INetTask<QuestionGetListRequest, QuestionGetListResponse> task,
					QuestionGetListResponse response) {
			//	list_question.setContextEmptyType(true, 2);
				list_question.doComplete();
				if (response.ResultCode == 200) {
					try {
						if (start_qid == 0) {
							if (adapter.getContainer() == null) {
								list_question.getListView().setAdapter(adapter);
							}
							adapter.getDataProvider().clear();
						}
						int retSize = response.Res.Questions.size();

						if (retSize > 0) {
							adapter.getDataProvider().addAll(
							response.Res.Questions);
							adapter.notifyDataSetChanged();
							if (retSize < GlobalSettings.PAGE_SIZE) {
								list_question.setHasMoreData(false);
							} else {
								list_question.setHasMoreData(true);
							}
						} else {
							if (adapter.getCount() > 0) {
								list_question.setHasMoreData(false);
							}
						}
						if (retSize > 0) {
							start_qid = response.Res.Questions.get(retSize - 1).Qid;
						//	text_empty.setVisibility(View.GONE);
						} else {
							adapter.notifyDataSetChanged();
						//	text_empty.setVisibility(View.VISIBLE);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					toast(R.string.server_unavailable);
				}
				if(adapter.getDataProvider()!=null&&adapter.getDataProvider().size()>0){
					list_question.setContextEmptyType(false, 2);
				}else{
					list_question.setContextEmptyType(true, 4);
				}
			}
		});
		add(task);
	}

	Button btn_question_status_all, btn_question_status_wait,
			btn_question_status_wait_cost, btn_question_status_finished,
			btn_sort_time, btn_sort_xuanshang, btn_sort_guanzhu;
	CheckBox btn_patient_all, btn_patient_male, btn_patient_famle,
			btn_patient_children, btn_patient_young, btn_patient_adult,
			btn_patient_old_man, btn_question_type_all;
	Button btn_reset_setting;

	ArrayList<Button> list_question_status = new ArrayList<Button>(),
			list_sort_time = new ArrayList<Button>();
	ArrayList<CheckBox> list_filter_asker = new ArrayList<CheckBox>(),
			list_question_type = new ArrayList<CheckBox>();

	@SuppressWarnings("unchecked")
	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			if (CommonUtility.isNull(view_filter)) {
				view_filter = LayoutInflater.from(getContext()).inflate(
						R.layout.view_filiter_question, null);
				view_filter.findViewById(R.id.rl_filter_root)
						.setOnClickListener(this);
				view_filter.findViewById(R.id.btn_reset_setting)
						.setOnClickListener(this);
				view_filter.findViewById(R.id.btn_ok).setOnClickListener(this);
				btn_question_status_all = (Button) view_filter
						.findViewById(R.id.btn_question_status_all);
				btn_question_status_all
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onFilter(v);
							}
						});
				btn_question_status_wait = (Button) view_filter
						.findViewById(R.id.btn_question_status_wait);
				btn_question_status_wait
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onFilter(v);
							}
						});
				btn_question_status_wait_cost = (Button) view_filter
						.findViewById(R.id.btn_question_status_wait_cost);
				btn_question_status_wait_cost
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onFilter(v);
							}
						});
				btn_question_status_finished = (Button) view_filter
						.findViewById(R.id.btn_question_status_finished);
				btn_question_status_finished
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onFilter(v);
							}
						});
				list_question_status.add(btn_question_status_all);
				list_question_status.add(btn_question_status_wait);
				list_question_status.add(btn_question_status_wait_cost);
				list_question_status.add(btn_question_status_finished);

				btn_sort_time = (Button) view_filter
						.findViewById(R.id.btn_sort_time);
				btn_sort_time.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onFilter(v);
					}
				});
				btn_sort_xuanshang = (Button) view_filter
						.findViewById(R.id.btn_sort_xuanshang);
				btn_sort_xuanshang.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onFilter(v);
					}
				});
				btn_sort_guanzhu = (Button) view_filter
						.findViewById(R.id.btn_sort_guanzhu);
				btn_sort_guanzhu.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onFilter(v);
					}
				});
				list_sort_time.add(btn_sort_time);
				list_sort_time.add(btn_sort_xuanshang);
				list_sort_time.add(btn_sort_guanzhu);

				btn_patient_all = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_all);
				btn_patient_all.setOnClickListener(this);
				btn_patient_male = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_male);
				btn_patient_male.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				btn_patient_famle = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_famle);
				btn_patient_famle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				btn_patient_children = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_children);
				btn_patient_children.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				btn_patient_young = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_young);
				btn_patient_young.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				btn_patient_adult = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_adult);
				btn_patient_adult.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				btn_patient_old_man = (CheckBox) view_filter
						.findViewById(R.id.btn_patient_old_man);
				btn_patient_old_man.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onAsk(v);
					}
				});
				list_filter_asker.add(btn_patient_all);
				list_filter_asker.add(btn_patient_male);
				list_filter_asker.add(btn_patient_famle);
				list_filter_asker.add(btn_patient_children);
				list_filter_asker.add(btn_patient_young);
				list_filter_asker.add(btn_patient_adult);
				list_filter_asker.add(btn_patient_old_man);

				btn_question_type_all = (CheckBox) view_filter
						.findViewById(R.id.btn_question_type_all);
				btn_question_type_all.setOnClickListener(this);
				lbl_question_type = (FlowLayout) view_filter
						.findViewById(R.id.lbl_question_type);

				btn_reset_setting = (Button) view_filter
						.findViewById(R.id.btn_reset_setting);
				btn_question_status_wait.setSelected(true);
				btn_question_status_finished.setSelected(true);
				btn_sort_time.setSelected(true);

				ArrayList<CacheCommon> caches = DBUtil
						.getInstance(getContext()).queryCache("Skilled");
				if (caches.size() > 0) {
					String data = caches.get(0).data;
					try {
						oType(new JSONArray(data));
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					new RequestTask(getContext(),
							Constant.URL.REQUEST_SYMPTOM_JSON,
							new RequestHandler(getContext(),
									new HandlerCallback() {

										@Override
										public void callback(Object o) {
											if (!CommonUtility.isNull(o)) {
												try {
													JSONArray array = new JSONArray(
															o.toString());
													oType(array);
													DBUtil.getInstance(
															getContext())
															.saveOrUpdate(
																	"Skilled",
																	o);
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}
									}), RequestTask.CHAR).execute();
				}

			}
			if (CommonUtility.isDoctor()) {
				btn_question_status_wait_cost.setVisibility(View.VISIBLE);
				btn_question_status_finished.setVisibility(View.GONE);
				btn_question_status_wait.setVisibility(View.VISIBLE);
			} else {
				btn_question_status_wait_cost.setVisibility(View.GONE);
				btn_question_status_finished.setVisibility(View.VISIBLE);
				btn_question_status_wait.setVisibility(View.GONE);
			}
			CommonUtility.addView((Activity) getContext(), view_filter,
					R.anim.push_left_in);
		} else if (id == R.id.btn_search) {
			startActivityForResult((new Intent(getContext(),
					SearchQuestionActivity.class)), 0);
		} else if (id == R.id.rl_filter_root) {
			if (!CommonUtility.isNull(view_filter)) {
				CommonUtility.removeView((Activity) getContext(), view_filter,
						R.anim.push_left_out);
			}
		} else if (id == R.id.btn_reset_setting) {
			if (CommonUtility.isDoctor()) {
				btn_question_status_wait.performClick();
			} else {
				btn_question_status_finished.performClick();
			}
			btn_sort_time.performClick();
			resetAllCheck(list_filter_asker);
			btn_patient_all.performClick();
			resetAllCheck(list_question_type);
			btn_question_type_all.performClick();
			setNavLeftBtnDrawable(R.drawable.icon_question_type);
			query();
		} else if (id == R.id.btn_ok) {
			boolean isStatusDefault = false;
			if (CommonUtility.isDoctor()) {
				isStatusDefault = btn_question_status_wait.isSelected();
			} else {
				isStatusDefault = btn_question_status_finished.isSelected();
			}
			boolean isSortDefault = btn_sort_time.isSelected();
			boolean isPatientDefault = btn_patient_all.isChecked();
			boolean isQuestionTypeDefault = btn_question_type_all.isChecked();
			boolean isGotoResetSetting = isStatusDefault && isSortDefault
					&& isPatientDefault && isQuestionTypeDefault;
			if (isGotoResetSetting) {
				btn_reset_setting.performClick();
			} else {
				query();
				setNavLeftBtnDrawable(R.drawable.btn_slide_menu_filter);
			}
		} else if (id == R.id.btn_patient_all) {
			resetAllCheck(list_filter_asker);
			btn_patient_all.setChecked(true);
			mRequest.sex = null;
			mRequest.ageRanges = null;
		} else if (id == R.id.btn_question_type_all) {
			resetAllCheck(list_question_type);
			btn_question_type_all.setChecked(true);
			mRequest.Symptoms = null;
		}
	}

	void query() {
		pageIndex = 0;
		CommonUtility.removeView((Activity) getContext(), view_filter,
				R.anim.push_left_out);
		mRequest.sex = new ArrayList<Integer>();
		if (btn_patient_male.isChecked()) {
			mRequest.sex.add(0);
		}
		if (btn_patient_famle.isChecked()) {
			mRequest.sex.add(1);
		}
		if (mRequest.sex.size() == 0) {
			mRequest.sex = null;
		}

		mRequest.ageRanges = new ArrayList<Integer>();
		if (btn_patient_children.isChecked()) {
			mRequest.ageRanges.add(1);
		}
		if (btn_patient_young.isChecked()) {
			mRequest.ageRanges.add(2);
		}
		if (btn_patient_adult.isChecked()) {
			mRequest.ageRanges.add(3);
		}
		if (btn_patient_old_man.isChecked()) {
			mRequest.ageRanges.add(4);
		}
		if (mRequest.ageRanges.size() == 0) {
			mRequest.ageRanges = null;
		}

		mRequest.Symptoms = new ArrayList<String>();
		for (CheckBox box : list_question_type) {
			if (box.isChecked()) {
				mRequest.Symptoms.add(box.getText().toString());
			}
		}
		if (mRequest.Symptoms.size() == 0) {
			mRequest.Symptoms = null;
		}
		mRequest.pageIndex = pageIndex;

		list_question.doPullRefreshing(true);
	}

	public void onDynamicFilter(View view) {
		btn_question_type_all.setChecked(false);
	}

	public void onAsk(View view) {
		btn_patient_all.setChecked(false);
	}

	private FlowLayout lbl_question_type;

	void oType(JSONArray array) {
		for (int i = 0; i < array.length(); i++) {
			try {
				String zhengzhuang = array.getJSONObject(i).getString("Name");
				CheckBox button = (CheckBox) LayoutInflater.from(getContext())
						.inflate(R.layout.item_filter_button, null);
				button.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onDynamicFilter(v);
					}
				});
				button.setText(zhengzhuang);
				lbl_question_type.addView(button);
				list_question_type.add(button);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void onSortAsk(View view) {
		resetAllCheck(list_filter_asker);
		btn_patient_all.setChecked(true);
	}

	private void resetAllCheck(ArrayList<CheckBox> checkBoxs) {
		for (CheckBox checkBox : checkBoxs) {
			checkBox.setChecked(false);
		}
	}

	public void onFilter(View view) {
		int id = view.getId();
		if (id == R.id.btn_question_status_all) {
			if (CommonUtility.isDoctor()) {
				mRequest.statuses = null;
			} else {
				mRequest.statuses = new ArrayList<Integer>();
				mRequest.statuses.add(1);
				mRequest.statuses.add(3);
			}
			mRequest.Is_Cost = null;
			resetBtnStatus(list_question_status, view);
		} else if (id == R.id.btn_question_status_wait) {
			mRequest.statuses = new ArrayList<Integer>();
			mRequest.statuses.add(1);
			mRequest.Is_Cost = null;
			resetBtnStatus(list_question_status, view);
		} else if (id == R.id.btn_question_status_wait_cost) {
			mRequest.statuses = new ArrayList<Integer>();
			mRequest.statuses.add(1);
			mRequest.Is_Cost = GlobalSettings.IS_TRUE;
			resetBtnStatus(list_question_status, view);
		} else if (id == R.id.btn_question_status_finished) {
			mRequest.statuses = new ArrayList<Integer>();
			mRequest.statuses.add(3);
			mRequest.Is_Cost = null;
			resetBtnStatus(list_question_status, view);
		} else if (id == R.id.btn_sort_time) {
			mRequest.Sort = null;
			resetBtnStatus(list_sort_time, view);
		} else if (id == R.id.btn_sort_xuanshang) {
			mRequest.Sort = "Cost";
			resetBtnStatus(list_sort_time, view);
		} else if (id == R.id.btn_sort_guanzhu) {
			mRequest.Sort = "FollowerCount";
			resetBtnStatus(list_sort_time, view);
		}
	}

	void resetBtnStatus(ArrayList<Button> btns, View view) {
		Button b = (Button) view;
		for (Button btn : btns) {
			btn.setBackgroundResource(R.drawable.btn_filter_unselected);
			btn.setTextColor(0xff609381);
			btn.setSelected(false);
		}
		b.setBackgroundResource(R.drawable.btn_filter_selected);
		b.setTextColor(getResources().getColor(R.color.white));
		b.setSelected(true);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = 0;
		pageIndex = 0;
		loadData(false);
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		CommonUtility.unRegisteReciver((Activity) getContext(),
				questionReceiver);
	}

	public static class ContactActionItem extends OActionItem {
		public String name;
		public String phone;
	}

	class QuestionReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				/**
				 * userType不为-1时为登陆后判断用户角色来决定是否显示问题界面右上角的免费提问按钮
				 */
				int userType = intent.getIntExtra(
						Constant.IDENTITY_KEY_USER_TYPE, -1);
				if (userType != -1) {
					// if (!CommonUtility.isDoctor()) {
					// setNavRightBtn("免费提问");
					// } else {
					// text_right.setVisibility(View.GONE);
					// }
				} else {
					boolean isRefresh = intent.getBooleanExtra(
							Constant.IDENTITY_KEY_1, false);
					if (isRefresh) {
						list_question.doPullRefreshing(true);
					} else {
						QuestionAnswer newData = JsonUtil.convert(
								intent.getStringExtra(Constant.IDENTITY_KEY),
								QuestionAnswer.class);
						for (int i = 0, size = adapter.getCount(); i < size; i++) {
							QuestionAnswer item = adapter.getItem(i);
							if (item.Qid == newData.Qid) {
								List<QuestionAnswer> dataProvider = adapter
										.getDataProvider();
								dataProvider.remove(i);
								dataProvider.add(i, newData);
								adapter.notifyDataSetChanged();
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
